package controllers

import (
	"blog/helper"
	"blog/library"
	"github.com/astaxie/beego"
	"strconv"
)

type ErrorController struct {
	beego.Controller
}

func (e *ErrorController) Error404() {
	e.notFound()
}

func (e *ErrorController) notFound(messages ...string) {
	var message = "很抱歉，你访问的页面找不到了"
	if e.IsAjax() {
		message = "很抱歉，你访问的接口找不到了"
	}

	if len(messages) > 0 {
		message = messages[0]
	}
	e.baseError(message, 404)
}

func (e *ErrorController) Error500() {
	e.serverError()
}

func (e *ErrorController) serverError() {
	e.baseError("服务内部出现错误，请联系管理员", 500)
}

func (e *ErrorController) serverDbError() {
	e.baseError("数据库错误，请联系管理员", 500)
}

func (e *ErrorController) baseError(message string, code int) {
	e.Data["pageHeader"] = false
	if e.IsAjax() {
		var apiFormatter helper.Api
		apiFormatter.Message = message
		apiFormatter.Code = code
		e.Data["json"] = apiFormatter
		e.ServeJSON()
		e.StopRun()
	} else {
		moduleName := beego.AppConfig.String("layout")
		if moduleName == "" {
			moduleName = "backend"
		} else {
			menuList := library.MenuHtml(e.Ctx.Request.RequestURI)
			e.Data["Menu"] = menuList
		}
		e.Layout = moduleName + "/" + "layout.html"
		codeArr := strconv.Itoa(code)
		total := len(codeArr)
		for i := 0; i < total; i++ {
			j := i + 1
			e.Data["errorCode"+strconv.Itoa(i)] = codeArr[i:j]
		}
		e.Data["errorMessage"] = message
		e.TplName = "error/error.html"
		_ = e.Render()
		e.StopRun()
	}
}
